package com.dede.tinypng;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author hsh
 * @date 2018/1/16 11:09.
 * @doc
 */
public class TinyPng {

    private final static String KEY = "F2M1mmW4eLCkQRD9BQtsqVDrMw6ypUG7";
    private final static String BASE64_KEY;

    static {
        byte[] encode = Base64.getEncoder().encode(KEY.getBytes());
        BASE64_KEY = new String(encode);
    }

    public static void shrinkImg(String filePath) {
        HttpURLConnection conn = null;
        FileInputStream fileInput = null;
        DataOutputStream out = null;
        BufferedReader reader = null;
        try {
            conn = (HttpURLConnection) new URL("https://api.tinify.com/shrink")
                    .openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Authorization", "Basic " + BASE64_KEY);
            conn.setRequestProperty("Cache-Control", "no-cache");
            conn.setRequestProperty("ContentType", "application/json");

            File file = new File(filePath);
            System.out.println("文件路径：" + file.getAbsolutePath());
            System.out.println("文件长度：" + file.length());

            out = new DataOutputStream(conn.getOutputStream());

            // 上传文件内容
            fileInput = new FileInputStream(file);
            byte[] bytes = new byte[4 * 1024];
            int len;
            while (-1 != (len = fileInput.read(bytes))) {
                out.write(bytes, 0, len);
            }
            close(fileInput);
            out.flush();
            close(out);

            int code = conn.getResponseCode();
            System.out.println("code:" + code);
            if (code == HttpURLConnection.HTTP_CREATED) {
                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String str;
                while (null != (str = reader.readLine())) {
                    builder.append(str);
                }
                String location = conn.getHeaderField("location");
                System.out.println("location:" + location);
                System.out.println(builder.toString());

                close(reader);
            } else {
                String message = conn.getResponseMessage();
                System.out.println("message:" + message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                close(fileInput, out, reader);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) conn.disconnect();
        }
    }

    public static void downloadImg(String fileName, String url) {
        HttpURLConnection conn = null;
        InputStream in = null;
        FileOutputStream out = null;
        try {
            conn = (HttpURLConnection) new URL(url)
                    .openConnection();
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");

            int code = conn.getResponseCode();
            System.out.println("code:" + code);
            if (code == HttpURLConnection.HTTP_OK) {
                in = conn.getInputStream();
                long contentLength = conn.getContentLengthLong();
                System.out.println(contentLength);
                out = new FileOutputStream(new File("TinyPng/result.jpg"));
                byte[] bytes = new byte[4 * 1024];
                int len;
                while (-1 != (len = in.read(bytes))) {
                    out.write(bytes, 0, len);
                }
                close(in, out);
            } else {
                String message = conn.getResponseMessage();
                System.out.println("message:" + message);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                close(in, out);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (conn != null) conn.disconnect();
        }
    }

    public static void close(Closeable... streams) throws IOException {
        for (Closeable stream : streams) {
            if (stream != null) {
                stream.close();
                stream = null;
            }
        }
    }
}
